/**
 * Copyright (C) cedarsoft GmbH.
 *
 * Licensed under the GNU General Public License version 3 (the "License")
 * with Classpath Exception; you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *         http://www.cedarsoft.org/gpl3ce
 *         (GPL 3 with Classpath Exception)
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3 only, as
 * published by the Free Software Foundation. cedarsoft GmbH designates this
 * particular file as subject to the "Classpath" exception as provided
 * by cedarsoft GmbH in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 3 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 3 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
 * or visit www.cedarsoft.com if you need additional information or
 * have any questions.
 */

package com.exadel.googleregistrator;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;

public class PhonesStorage {
    private static final String ROOT = "phonelist";
    private static final String CHILD = "phone";
    private static final String FILENAME = "src//main//resources//phones.xml";

    Element root;
    Document document;

    public PhonesStorage() {
        File xmlFile = new File(FILENAME);
        if (xmlFile.exists())
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            try {
                builder = factory.newDocumentBuilder();
                document = builder.parse(xmlFile);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            root = (Element) document.getElementsByTagName(ROOT).item(0);
        }
        else createDocument();
    }

    public void addPhone(String phoneNumber) {
        Element childElement = document.createElement(CHILD);
        root.appendChild(childElement);
        Text textNode = document.createTextNode(phoneNumber);
        childElement.appendChild(textNode);
        saveChanges();
    }

    public String getPhone() {
        Element element = (Element) document.getElementsByTagName(CHILD).item(0);
        String result = element.getChildNodes().item(0).getNodeValue();
        element.getParentNode().removeChild(element);
        document.normalize();
        saveChanges();
        return result;
    }

    private void saveChanges() {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer tFormer;
        try {
            tFormer = tFactory.newTransformer();
            Result dest1 = new StreamResult(FILENAME);
            Source source = new DOMSource(document);
            tFormer.transform(source, dest1);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }

    private void createDocument() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        try {
            builder = factory.newDocumentBuilder();
            document = builder.newDocument();
            if (document == null)
                throw new NullPointerException();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        root = document.createElement(ROOT);
        document.appendChild(root);
    }
}





